package com.example.rockscissorspapergame.service;

import com.example.rockscissorspapergame.Constants;
import ohos.aafwk.ability.Ability;
import ohos.aafwk.content.Intent;
import ohos.rpc.*;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;

/**
 * 用来实现石头剪刀布游戏主机端远程端协同的 ServiceAbility
 */
public class ServiceAbility extends Ability {
    private static final HiLogLabel LABEL_LOG = new HiLogLabel(0, 0x01007, "ServiceAbility");

    @Override
    public void onStart(Intent intent) {
        HiLog.error(LABEL_LOG, "ServiceAbility::onStart");
        super.onStart(intent);
    }

    @Override
    public void onBackground() {
        super.onBackground();
        HiLog.info(LABEL_LOG, "ServiceAbility::onBackground");
    }

    @Override
    public void onStop() {
        super.onStop();
        HiLog.info(LABEL_LOG, "ServiceAbility::onStop");
    }

    @Override
    public void onCommand(Intent intent, boolean restart, int startId) {
        HiLog.info(LABEL_LOG, "ServiceAbility::onCommand");
    }

    @Override
    public IRemoteObject onConnect(Intent intent) {
        HiLog.info(LABEL_LOG, "ServiceAbility::onConnect");
        return new GameRemoteObject("GameRemoteObject").asObject();
    }

    @Override
    public void onDisconnect(Intent intent) {
        HiLog.info(LABEL_LOG, "ServiceAbility::onConnect");
    }

    /**
     * RemoteObject 类，用于接收跨端信息
     */
    private static class GameRemoteObject extends RemoteObject implements IRemoteBroker {

        public GameRemoteObject(String descriptor) {
            super(descriptor);
        }

        @Override
        public IRemoteObject asObject() {
            return this;
        }

        @Override
        public boolean onRemoteRequest(int code, MessageParcel data, MessageParcel reply, MessageOption option) {
            // 接收跨端信息
            String message = data.readString();
            // 通过 ConnectionHelper 将信息回调给 PageAbility
            ConnectionHelper.getInstance().sendMessage(message);
            // 回传结果给信息发送者
            reply.writeInt(Constants.ERR_OK);
            return true;
        }
    }
}